package cn.itcast.mq.listener;

import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.LocalTime;

@Component
public class SpringRabbitListener {

//    @RabbitListener(queues = "simple.queue")
//    public void listenSimpleQueueMessage(String msg) throws InterruptedException{
//        System.out.println("spring 消费者接收到消息:[" + msg + "]");
//    }

    @RabbitListener(queues = "simple.queue")
    public void listenWorkQueue1(String msg) throws InterruptedException{
        System.out.println("消费者1接收到消息:[" + msg + "]" + LocalTime.now());
        Thread.sleep(20);// 每隔20ms接收一个消息
    }

    @RabbitListener(queues = "simple.queue")
    public void listenWorkQueue2(String msg) throws InterruptedException{
        System.out.println("消费者2接收到消息:[" + msg + "]" + LocalTime.now());
        Thread.sleep(200);// 每隔200ms接收一个消息,模拟处理时间慢
    }

    @RabbitListener(queues = "fanout.queue1")
    public void listenFanoutQueue1(String msg){
        System.out.println("路由模式下消费者1收到的Fanout消息[" + msg + "]");
    }

    @RabbitListener(queues = "fanout.queue2")
    public void listenFanoutQueue2(String msg){
        System.out.println("路由模式下消费者2收到的Fanout消息[" + msg + "]");
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.queue1"),
            exchange = @Exchange(name = "bugger.direct",type = ExchangeTypes.DIRECT),
            key = {"key1","key2"}
    )) // 这个消费者注解内还可以绑定交换机和队列以及接收指定路由键
    public void listenDirectQueue1(String msg){
        System.out.println("队列1收到的消息[" + msg + "]");
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.queue2"),
            exchange = @Exchange(name = "bugger.direct",type = ExchangeTypes.DIRECT),
            key = {"key1","key3"}
    )) // 这个消费者注解内还可以绑定交换机和队列以及接收指定路由键
    public void listenDirectQueue2(String msg){
        System.out.println("队列2,收到的消息[" + msg + "]");
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "topic.queue1"),
            exchange = @Exchange(name = "bugger.topic",type = ExchangeTypes.TOPIC),
            key = "china.#"
    )) // 匹配所有china开头的路由键,*可以表示一个任意单词,#表示任意数量任意词
    public void listenTopicQueue1(String msg){
        System.out.println("topic,queue1收到的消息[" + msg + "]");
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "topic.queue2"),
            exchange = @Exchange(name = "bugger.topic",type = ExchangeTypes.TOPIC),
            key = "*.news"
    )) // 一个单词.news的路由键,*可以表示一个任意单词,#表示任意数量任意词
    public void listenTopicQueue2(String msg){
        System.out.println("topic,queue2收到的消息[" + msg + "]");
    }

}
